package com.beerandjesus.sportofkings.handicapper.dao;

import com.beerandjesus.sportofkings.handicapper.model.TurfSire;
import com.beerandjesus.sportofkings.handicapper.model.TurfSireImpl;
import org.hibernate.SQLQuery;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.apache.log4j.Logger;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.util.List;
import java.math.BigDecimal;

/**
 * Date: Sep 8, 2012
 * Time: 6:38:05 PM
 */
public class TurfSireHibernateDAO extends AbstractHibernateDAO implements TurfSireDAO {

    private BaseSireDataFactory factory = new BaseSireDataFactory();
    private String[] baseDataFiles;
    private static final Logger LOG = Logger.getLogger(TurfSireHibernateDAO.class);

    public void buildDatabase() throws DAOException {
        if (getBaseDataFiles() == null || getBaseDataFiles().length < 1) {
            throw new DAOException("No base data files provided");
        }
        dropAndCreate(DROP_TABLE_STMT, CREATE_TABLE_STMT, LOG);

        List<BaseSireData> data;
        try {
            data = factory.getBaseSireData(getBaseDataFiles());
        } catch (IOException e) {
            throw new DAOException("Error getting sire data", e);
        }
        for (BaseSireData d : data) {
            BigDecimal percentage = factory.getWinPercentage(d);
            TurfSireImpl sire = new TurfSireImpl();
            sire.setName(d.getName());
            sire.setWinPercentage(percentage);
            getSession().save(sire);
        }

    }

    public int getRowCount() throws DAOException {
        Query q = getSession().createQuery("select count(t) from TurfSireImpl t");
        Long count = (Long) q.uniqueResult();
        return (count == null ? 0 : count.intValue());
    }

    public TurfSire getTurfSireByName(String name) throws DAOException {
        if (StringUtils.isEmpty(name)) {
            return null;
        }
        Query q = getSession().createQuery("from TurfSireImpl where name = :name");
        q.setString("name", name.toUpperCase());
        return (TurfSire) q.uniqueResult();
    }

    public String[] getBaseDataFiles() {
        return baseDataFiles;
    }

    public void setBaseDataFiles(String[] baseDataFiles) {
        this.baseDataFiles = baseDataFiles;
    }
}
